"""
用户购买数据库操作类
提供用户购买记录的批量查询和插入操作
"""

import time
import aiomysql
from typing import List, Dict, Any, Literal
from db.operations import BaseOperations
from db import DatabaseConnection, db_connection


class UserPurchasesOperations(BaseOperations):
    """用户购买数据库操作类"""

    def __init__(self):
        # 继承BaseOperations，指定表名为user_purchases
        super().__init__("user_purchases")
        self.db_connection: DatabaseConnection = db_connection

    async def batch_query_purchases(
        self, user_book_ids: List[Dict[str, int]] = None
    ) -> List[Dict[str, Any]]:
        """
        批量查询用户购买记录
        可以根据用户ID列表或图书ID列表进行查询

        Args:
            user_book_ids : List[Dict[str, int]]: 用户ID和图书ID列表
            每个字典可以包含：
            {
                "user_id": 1,
                "book_id": 123
            }

        Returns:
            List[Dict[str, Any]]: 购买记录列表
            每个字典包含：
            {
                "user_id": 1,
                "book_id": 123,
                "price": 29.8,
                "created_at": 1686825600,
                "updated_at": 1686825600
            }
        """
        params = []

        # 如果没有提供查询条件，返回空列表
        if not user_book_ids:
            return []

        specific_pairs = []

        for item in user_book_ids:
            user_id = item.get("user_id")
            book_id = item.get("book_id")
            # 用户-图书
            if user_id and book_id:
                specific_pairs.append((user_id, book_id))

        # 构建OR条件组合
        or_conditions = []

        # 添加特定用户-图书对的条件
        if specific_pairs:
            pair_conditions = []
            for user_id, book_id in specific_pairs:
                pair_conditions.append("(user_id = %s AND book_id = %s)")
                params.extend([user_id, book_id])
            or_conditions.append("(" + " OR ".join(pair_conditions) + ")")

        if not or_conditions:
            return []

        where_clause = " OR ".join(or_conditions)
        order_by = "updated_at DESC"

        return await self.batch_query(
            where_clause=where_clause, params=tuple(params), order_by=order_by
        )

    async def batch_insert_purchases(self, purchases_data: List[Dict[str, Any]]) -> int:
        """
        批量插入用户购买记录

        Args:
            purchases_data (List[Dict[str, Any]]): 购买记录数据列表
            每个字典应包含购买记录的字段，例如：
            {
                "user_id": 1,
                "book_id": 123,
                "price": 29.8,
                "created_at": 1686825600,  # 创建时间戳（可选，自动生成）
                "updated_at": 1686825600   # 更新时间戳（可选，自动生成）
            }

        Returns:
            int: 成功插入的购买记录数量
        """
        if not purchases_data:
            return 0

        # 验证必要字段
        valid_data = []
        for data in purchases_data:
            if "user_id" not in data or "book_id" not in data or "price" not in data:
                print("警告：数据中缺少必要字段(user_id, book_id, price)，跳过该条记录")
                continue
            valid_data.append(data.copy())  # 创建副本避免修改原数据

        if not valid_data:
            return 0

        # 调用父类的批量插入方法，使用skip策略（避免重复购买）
        return await self.batch_insert(valid_data, on_duplicate="skip")
